package erabbit.net.camerabot;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.media.AudioManager;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.idl.face.platform.FaceConfig;
import com.baidu.idl.face.platform.FaceSDKManager;
import com.baidu.idl.face.platform.FaceStatusEnum;
import com.baidu.idl.face.platform.IDetectStrategy;
import com.baidu.idl.face.platform.IDetectStrategyCallback;
import com.baidu.idl.face.platform.ui.FaceSDKResSettings;
import com.baidu.idl.face.platform.ui.utils.VolumeUtils;
import com.baidu.idl.face.platform.utils.APIUtils;
import com.baidu.idl.face.platform.utils.Base64Utils;
import com.baidu.idl.face.platform.utils.CameraPreviewUtils;
import com.facepp.library.util.ConUtil;
import com.facepp.library.util.DialogUtil;
import com.facepp.library.util.Util;
import com.megvii.facepp.sdk.Facepp;
import com.megvii.licensemanager.sdk.LicenseManager;

import junit.framework.Test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import erabbit.net.camerabot.utils.FileUtils;

public class TestActivity extends Activity implements CameraPreview.FaceCallback {

    public static final String TAG = TestActivity.class.getSimpleName();
    public static final String DETECT_CONFIG = "FaceOptions";

    // View
    protected View mRootView;
    protected CameraPreview mSurfaceView;
    protected SurfaceHolder mSurfaceHolder;
    protected TextView mTipsView;
    protected LinearLayout mImageLayout;
    ImageView mFaceOverlayView;
    // 人脸信息
    protected FaceConfig mFaceConfig;
    // 显示Size
    protected int mDisplayWidth = 0;
    protected int mDisplayHeight = 0;
    // 状态标识
    // 相机
    // 监听系统音量广播
    protected BroadcastReceiver mVolumeReceiver;
    Handler handler = new Handler();
    Facepp facepp;

    boolean startDetect = true;
    boolean startTakePicture = false;
    TextView countdown;
    int countdownTime = 10;
    final int detectRate = 5;
    int curNum = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_test);
        DisplayMetrics dm = new DisplayMetrics();
        Display display = this.getWindowManager().getDefaultDisplay();
        display.getMetrics(dm);
        mDisplayWidth = dm.widthPixels;
        mDisplayHeight = dm.heightPixels;

        FaceSDKResSettings.initializeResId();
        mFaceConfig = FaceSDKManager.getInstance().getFaceConfig();
        mFaceOverlayView = (ImageView) findViewById(R.id.detect_surface_overlay);
        mRootView = this.findViewById(R.id.detect_root_layout);
        mSurfaceView = (CameraPreview) findViewById(R.id.detect_surface_view);
        countdown = (TextView) findViewById(R.id.countdown);
        countdown.setVisibility(View.INVISIBLE);
        mSurfaceView.setFaceCallback(this);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.setSizeFromLayout();
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);


    }


    @Override
    protected void onResume() {
        super.onResume();
        startDetect = true;
        startTakePicture = false;
        countdownTime = 10;
        countdown.setVisibility(View.INVISIBLE);
        network();
    }


    private void network() {

        if (Util.API_KEY == null || Util.API_SECRET == null) {
            if (!ConUtil.isReadKey(this)) {
                DialogUtil mDialogUtil = new DialogUtil(this);
                mDialogUtil.showDialog(getResources().getString(R.string.key_secret));
            }
        }

        if (Facepp.getSDKAuthType(ConUtil.getFileContent(this, R.raw
                .megviifacepp_0_4_7_model)) == 2) {// 非联网授权
            //authState(true);
            return;
        }

        final LicenseManager licenseManager = new LicenseManager(this);
        licenseManager.setExpirationMillis(Facepp.getApiExpirationMillis(this, ConUtil.getFileContent(this, R.raw
                .megviifacepp_0_4_7_model)));

        String uuid = ConUtil.getUUIDString(TestActivity.this);
        long apiName = Facepp.getApiName();

        licenseManager.setAuthTimeBufferMillis(0);

        licenseManager.takeLicenseFromNetwork(uuid, Util.API_KEY, Util.API_SECRET, apiName,
                LicenseManager.DURATION_30DAYS, "Landmark", "1", true, new LicenseManager.TakeLicenseCallback() {
                    @Override
                    public void onSuccess() {
                        //authState(true);
                        //授权成功
                        Log.i(TAG, "授权成功");
                        facepp = new Facepp();
                        String error = facepp.init(TestActivity.this, ConUtil.getFileContent(TestActivity.this, R.raw.megviifacepp_0_4_7_model));
                        if (error != null) {
                            Log.e("initError", error);
                        }
                        Facepp.FaceppConfig config = facepp.getFaceppConfig();
                        config.minFaceSize = 100;
                        config.interval = 2000;

                        config.one_face_tracking = 1;
                        config.rotation = 0;
                        config.roi_left = 0;
                        config.roi_top = 0;
                        config.roi_bottom = 480;
                        config.roi_right = 640;
                        config.detectionMode = Facepp.FaceppConfig.DETECTION_MODE_NORMAL;

//                        byte[] dataT = null;
//                        Bitmap bitmapT = BitmapFactory.decodeResource(getResources(), R.drawable.test2);
//                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                        bitmapT.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//                        dataT = baos.toByteArray();
//                        dataT = ConUtil.getGrayscale(bitmapT);
//                        Facepp.Face[] faces = facepp.detect(dataT, bitmapT.getWidth(), bitmapT.getHeight(), Facepp.IMAGEMODE_GRAY);
//
//                        if (faces != null) {
//                            Log.i(TAG, "faces.length=" + faces.length);
//                        }
                    }

                    @Override
                    public void onFailed(int i, byte[] bytes) {
                        //authState(false);
                    }
                });
    }


    @Override
    public void callback(Bitmap bitmap) {

        if (facepp != null) {

            if (startDetect) {

                curNum++;
                if (curNum % detectRate == 0) {
                    curNum = 0;
                } else {
                    return;
                }
                byte[] dataT = ConUtil.getGrayscale(bitmap);
                Facepp.Face[] faces = facepp.detect(dataT, bitmap.getWidth(), bitmap.getHeight(), Facepp.IMAGEMODE_GRAY);

                //检测到人脸后
                if (faces != null && faces.length > 0) {
                    startDetect = false;
                    Log.e(TAG, "faces.length=" + faces.length);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            countdown.setVisibility(View.VISIBLE);
                            countdown.setText(String.valueOf(countdownTime));
                            countdownTime--;
                            if (countdownTime == 0) {
                                startTakePicture = true;
                            } else {
                                handler.postDelayed(this, 1000 * 1);
                            }
                        }
                    }, 0); //每隔1s执行
                }
            }

            if (startTakePicture) {
                bitmap = FileUtils.waterTextMark(TestActivity.this, bitmap, "酷图软件");
                MyApplication.bmp = bitmap;
                final String picUrl = FileUtils.saveBitmap(bitmap);
                Intent intent = new Intent(TestActivity.this, ShowImageActivity.class);
                intent.putExtra("picUrl", picUrl);
                startActivity(intent);
                startTakePicture = false;
            }

        }
    }
}
